<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="问卷标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入问卷标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>



      <el-form-item label="名称" prop="targetName">
        <el-input
          v-model="queryParams.targetName"
          placeholder="请输入辅导员名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>



      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
     <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:complaint:add']"
        >新增</el-button>
      </el-col> -->

      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:complaint:remove']"
        >删除</el-button>
      </el-col> -->
      <!--           v-hasPermi="['system:complaint:export']" -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"

        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="releaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
 
      <el-table-column label="问卷标题" align="center" prop="title" />
      <el-table-column label="辅导员名称" align="center" prop="targetName" />
      <el-table-column label="学工处" align="center" prop="jwcAvgScore" />
      <el-table-column label="学院领导" align="center" prop="ejxyldAvgScore" />
      <el-table-column label="辅导员" align="center" prop="fdyAvgScore" />
      <el-table-column label="学生" align="center" prop="xsAvgScore" />
      <el-table-column label="最终成绩（学工*0.15 + 辅导员*0.15 + 学院领导 * 0.2 + 学生*0.5）" align="center" prop="finalScore" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
         
          >查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 问卷详情对话框 -->
    <el-dialog
      title="问卷详情"
      :visible.sync="resultDialogVisible"
      :fullscreen="true"
      :before-close="clearData"
   >
    <div class="detail">
        <!-- <h1>{{"得分：" + this.statistics.totalScore}}</h1> -->
         <!-- <h1>{{"得分：" + curRow.finalScore}}</h1> -->
        <div class="question" v-for="(item,idx) in statistics.questions" :key="idx">
              <div class="title">
                {{item.name}}
              </div>
              <div v-if="item.type != 0" class="dataTable">
                  <div class="optionTable">
                    <el-table :data="item.options" border style="width: 100%">
                        <el-table-column label="选项名称" prop="name"></el-table-column>
                        <el-table-column label="小计" prop="value"></el-table-column>

                        <el-table-column label="比例" >
                          <template slot-scope="scope">
                            {{(scope.row.value / item.totalSelectCount * 100).toFixed(2) + '%'}}
                          </template>

                        </el-table-column>
                    </el-table>
                  </div>
                  <div :id="'chart_idx_'+item.index" class="chart">
                      
                  </div>
              </div>
              <div v-if="item.type == 0"  class="dataTable">
                <el-table :data="item.textList" border style="width: 100%">
                  <el-table-column label="填写内容" >
                     <template slot-scope="scope">
                        {{scope.row}}
                      </template>

                  </el-table-column>
                </el-table>
           
              </div>
              <div class="score">

              </div>
        </div>
            <!-- <div id="chart_idx_1" class="chart">

              </div> -->

    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import { listRelease, getRelease, delRelease, addRelease, updateRelease } from "@/api/questionnaire/release";
import { queryAnswerList,ratioScore } from "@/api/questionnaire/answer";

import { get} from "@/api/questionnaire/question";
export default {
  name: "Release",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      releaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        questions: null,
        startTime: null,
        endTime: null,
        status: null,
        qId: null,
        stuYearId: null,
        stuYearName: null,
        teacherId: null,
        teacherName: null,
        deptId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //
      resultDialogVisible:false,
      //统计结果
      statistics:{
        totalScore:null,
        questions:[
        
        ]
      },
      curRow:null,
    };
  },
  created() {
    this.getList();
  },
  methods: {

    clearData(){
      this.statistics={totalScore:null,
        questions:[
        
        ]};
      this.resultDialogVisible = false;
    },
    createChart(chartId, option) {
          const chart = this.$echarts.init(document.getElementById(chartId));
          chart.setOption(option);
    },
    buildStatistics(row){
        get(row.questionnaireId).then(res=>{
          let questions = JSON.parse(res.data.questions);
          for(let i = 0;i < questions.length ; i++){
            let question = {
               index:questions[i].index,
               name:questions[i].name,
               type:questions[i].type,
               options:[],
               totalSelectCount:0,
            }
            if( questions[i].type != 0){
               let options = questions[i].options;
                for(let j = 0;j < options.length;j++ ){
                    let option = {
                      value:0,
                      name:options[j].content
                    }
                    question.options.push(option);
                }
            }else{
              question.textList=[];
            }

             this.statistics.questions.push(question);
        }

        });

        
    },
    async handleDetail(row){
      this.curRow = row;
      await this.buildStatistics(row);
   
      this.resultDialogVisible = true;
        let totalScore = 0;
        queryAnswerList({questionnaireId:row.questionnaireId,targetId:row.targetId}).then(res=>{
       
           for(let i = 0;i< res.data.length;i++){
              let answer = res.data[i];
              //将答卷转化成JSON
              let questions = JSON.parse(answer.questions);
              for(let j = 0;j< questions.length;j++){
                let question = questions[j];
                  if(question.type != 0){
            
                      let options = question.options;
                      for(let k = 0;k< options.length;k++){
                        let option = options[k];
                        if(option.isSelected == 1){
    
                          totalScore = totalScore + Number.parseInt(option.score);
                          let value = this.statistics.questions[j].options[k].value;
                          this.statistics.questions[j].options[k].value = value + 1;
                            this.statistics.questions[j].totalSelectCount = this.statistics.questions[j].totalSelectCount + 1;
                     
                        }
                      }
                      
                  }else{
                        this.statistics.questions[j].textList.push(question.text);
                  }
              }
           }
           this.statistics.totalScore  = totalScore/ res.data.length;

            //生成图表
           for(let i = 0;i< this.statistics.questions.length;i++){
            if(this.statistics.questions[i].type != 0){

            
              let question = this.statistics.questions[i];
              let option = {
               title: {
             
                    left: 'center',
                    top:"50"
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '<br/>{b} : {c} ({d}%)'
                },
                label: {
                    show: true,
                    formatter: '{b}: {d}%' // 显示名称和百分比
                },
  
              
                series: [
                    {
                        type: 'pie',
                        radius: '30%',
                    
                        data: [
                            // { value: 10, name: '选项1' },
                            // { value: 50, name: '选项2' },
                            // { value: 50, name: '选项3' }
                        ]
                    }
                ]
            }
              
              let options = question.options;
                    for(let k = 0;k< options.length;k++){
                        option.series[0].data.push(options[k]);
                }
                      
                  
            
              this.createChart("chart_idx_" + this.statistics.questions[i].index,option);

              this.$forceUpdate();
           }
           }
           
              console.log(this.statistics);
        })
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      ratioScore(this.queryParams).then(response => {
        this.releaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        questions: null,
        startTime: null,
        endTime: null,
        status: null,
        qId: null,
        stuYearId: null,
        stuYearName: null,
        teacherId: null,
        teacherName: null,
        deptId: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加【请填写功能名称】";
    },
    /** 修改按钮操作 */
    // handleUpdate(row) {
    //   // this.reset();
    //   // const id = row.id || this.ids
    //   // getRelease(id).then(response => {
    //   //   this.form = response.data;
    //   //   this.open = true;
    //   //   this.title = "修改【请填写功能名称】";
    //   // });
      
    // },
       handleUpdate(row) {

        //问卷表的id
      const nid = row.id || this.ids;
            //  let data = {};
                    // Object.assign(data,{
                    //     questions:JSON.parse(row.questions),
                    //     title:row.title,
                    //     id:row.id
                    // });

                      const teacherId = row.teacherId 
        this.$router.push({
          path: 'detail', 
          query: { id: nid,teacherId:teacherId}
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRelease(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRelease(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(function() {
        return delRelease(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('comprehensive/answer/export', {
        ...this.queryParams
      }, `release_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
  .chart{
    width: 100%;
    height: 600px;
  }
  .detail{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;

  }
  .question{
    padding-bottom:10px ;
      width: 100%;
  }
  .title{
    font-size: 18px;
    font-weight:  bold;
  }
  .dataTable{
    padding: 10px 0px;
    text-align: left;
  }

</style>
